<?php

require_once $_SERVER['DOCUMENT_ROOT'] . "/kernel/starter.php";
Module::Init('system:structure');
BDS::Init();
$ok = true;
$sql = "";

$request = $_REQUEST;
$ai = BDSFields::NextId();

if (isset($request['fields'])) {
    $fields = array();
    foreach ($request['fields'] as $i => $field) {
        if (!$field['exists']) {
            $field['id'] += $ai;
        }
        if (isset($field['code']) && !$field['code']) {
            $field['code'] = "field_" . $field['id'];
        }
        if (isset($field['container_id']) && !$field['container_id']) {
            $field['container_id'] = "NULL()";
        }elseif(isset($field['container_id']) && !$field['exists']){
            $field['container_id'] += $ai;
        }
        $fields[] = $field;
    }
    foreach ($fields as $sqlData) {
        if ($sqlData['exists']) {
            BDSFields::Delete($sqlData['id']);
            $ok = true;
        }
        unset($sqlData['exists']);
        if (!isset($sqlData['drop'])) {
            $ok = BDSFields::Create($sqlData);
        }
    }
}


if ($ok) {
    print json_encode(array('type' => "ok", "msg" => "Fields saved", "sql" => $sql));
} else {
    print json_encode(array('type' => "error", "msg" => "Fields save failed", "sql" => $sql));
}